import yaml
import json
from typing import Dict
# from video import scheme_start,scheme_stop,scheme_check

def json2yaml(jsonFile,isFile=True):
    if isFile:
        with open(jsonFile,encoding='utf-8') as f:
            json_data=json.load(f)
    else:
        json_data=jsonFile
    fileName=json_data['fileName']
    new_modules={}
    for k,v in json_data.items():
        if isinstance(v,list):#modules, connections
            datas=json_data[k]
            # if k=='modules':
            for data in datas:#input output
                for kk,vv in data.items():
                    if vv[0]=='[':#list
                        items=json.loads(data[kk])
                        new_items={}
                        for item in items:
                            if item['key'] !='':
                                new_items[item['key']]=item['value'] 
                        data[kk]=new_items
                for kk,vv in data.items():
                    if kk=='name':
                        new_modules[vv]=data
                        new_modules[vv].pop('name')
                        if new_modules[vv]['output args'] != {}:
                            new_modules[vv]['output args']=list(new_modules[vv]['output args'].keys())
                        break
    json_data['modules']=new_modules
    yaml_data=yaml.dump(json_data,sort_keys=False)
    with open('/workspace/schemes/'+fileName,'w',encoding='utf-8') as f:
        f.write(yaml_data)

camera_dict:Dict[str,str]={
    '0':'192.168.1.16',
    '1':'192.168.1.10',
    '2':'192.168.1.8',
    '3':'192.168.1.4',
    '4':'192.168.1.5',
    '5':'192.168.1.12'
}

TASK_NUM=3
CAMERA_NUM=5

def get_unique_int(num1:int,num2:int):
    return num1*(max(num1,num2)+1)+num2

def task_json2yml(jsonFile):
    taskId=jsonFile['taskId']
    cameraId=jsonFile['cameraId']
    taskId_num=int(taskId)
    cameraId_num=int(cameraId)

    if taskId_num < TASK_NUM and cameraId_num < CAMERA_NUM:
        with open('/workspace/schemes/original/'+taskId+'.yml','r') as f:
            yaml_data=yaml.safe_load(f)
            yaml_data['modules']['image harmony gRPC']['input args']['DeviceAddress']=camera_dict[cameraId]
        with open('/workspace/schemes/'+str(get_unique_int(taskId_num,cameraId_num))+'.yml','w') as f:
            yaml.safe_dump(yaml_data,f)
    # import requests
    # if scheme_start(int(str(taskId)+str(cameraId))):
    #     return 'OK'
    # else:
    #     return 'NO'



if __name__ =='__main__':
    path='/workspace/src/app/api/test1.json'
    with open(path,encoding='utf-8') as f:
            json_data=json.load(f)
    task_json2yml(json_data)